<template>
  <div>
    <!-- 全局组件 -->
    <Category :show="show"></Category>
    <el-card style="margin: 10px 0">
      <div v-show="show === 0">
        <!-- 添加平台属性按钮 -->
        <el-button
          :disabled="categoryStore.c3Id ? false : true"
          :icon="Plus"
          type="primary"
          @click="OneShow"
          >添加平台属性</el-button
        >
        <!-- table表格 -->
        <el-table border stripe style="margin: 10px 0" :data="data">
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <!-- tag标签 -->
              <el-tag
                :type="i.id % 2 === 0 ? 'success' : 'warning'"
                v-for="(i, index) in row.attrValueList"
                :key="index"
                style="margin: 0 5px"
              >
                {{ i.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row, $index }">
              <el-button
                size="small"
                :icon="Edit"
                type="warning"
                @click="edit(row)"
              ></el-button>
              <el-popconfirm
                :title="`确定删除${row.attrName}吗`"
                @confirm="clear(row)"
              >
                <template #reference>
                  <el-button
                    size="small"
                    :icon="Delete"
                    type="danger"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="show === 1">
        <!-- 属性名称input -->
        <!-- 表单验证 -->
        <el-form :inline="true" :model="addParams" :rules="rules" ref="formVC">
          <!-- prop名称必须与model收集库内的名称一致 -->
          <el-form-item prop="attrName" label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="addParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- 添加属性值按钮 -->
        <el-button
          type="primary"
          :icon="Plus"
          @click="addAttr"
          :disabled="addParams.attrName ? false : true"
          >添加属性值</el-button
        >
        <!-- 取消按钮 -->
        <el-button type="primary" @click="ZeroShow">取消</el-button>
        <!-- 表格区 -->
        <el-table border style="margin: 10px 0" :data="addParams.attrValueList">
          <!-- 表格序号 -->
          <el-table-column
            label="序号"
            width="80px"
            align="center"
            type="index"
          ></el-table-column>
          <!-- 表格属性值 -->
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                v-if="row.show"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
                size="small"
                :ref="(el) => (formArr[$index] = el)"
              ></el-input>
              <div v-else @click="toWrite(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <!-- 表格操作 -->
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-popconfirm
                :title="`确定删除${row.valueName}?`"
                width="200px"
                @confirm="deleteOne($index)"
              >
                <template #reference>
                  <el-button
                    :icon="Delete"
                    size="small"
                    type="danger"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 保存按钮 -->
        <el-button
          type="primary"
          :disabled="addParams.attrValueList.length == 0 ? true : false"
          @click="save"
          >保存<el-icon class="el-icon--right"><Pointer /></el-icon
        ></el-button>
        <!-- 取消按钮 -->
        <el-button type="primary" @click="ZeroShow">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, Edit, Pointer } from "@element-plus/icons-vue";
//引入请求
import {
  attrInfo,
  reqAddOrUpdateAttr,
  deleteAttr,
} from "@/api/product/attr/index";
//引入仓库
import useCategoryStore from "@/stores/category";
import { watch, ref, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
// lodash 深拷贝
import cloneDeep from "lodash/cloneDeep";
//调用小仓库
let categoryStore = useCategoryStore();

//监听c3id变化
watch(
  () => categoryStore.c3Id,
  () => {
    // 监视c3id的变化,清空数据框
    data.value = [];

    // 如果c3Id没有数据就不发送请求
    if (categoryStore.c3Id === "") return;
    // 调用请求
    getData();
  }
);
//定义data数据
let data = ref([]);
//定义状态,控制场景切换
let show = ref(0);
// 表单聚焦
// 获取表单ref
let formArr = ref([]);

//新增一个属性的需要携带的参数
let addParams: any = ref({
  attrName: "", //属性的名字
  attrValueList: [
    // {
    // valueName: "",//属性值的
    // },
  ],
  categoryId: "", //某一个三级分类ID
  categoryLevel: 3, //给某一个三级分类添加属性
});
//添加属性值按钮的回调
let addAttr = () => {
  addParams.value.attrValueList.push({
    valueName: "",
    show: true,
  });
  //  立即获取焦点
  nextTick(() => {
    formArr.value[formArr.value.length - 1].focus();
  });
};
//平台属性按钮的回调
let OneShow = () => {
  // 清空数据
  Object.assign(addParams.value, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryStore.c3Id, //将当前点击的三级id保存,便于发送请求
    categoryLevel: 3,
  });
  show.value = 1;
};
//取消按钮的回调
let ZeroShow = () => {
  show.value = 0;
};
//保存按钮的回调
let save = async () => {
  //整理参数
  // addParams.value.categoryId = categoryStore.c3Id   //点击平台属性按钮时已获取
  //参数整理完毕发请求
  try {
    // 表单校验通过
    await formVC.value.validate();
    //发送请求
    await reqAddOrUpdateAttr(addParams.value);
    //请求成功弹框
    ElMessage({
      message: addParams.value.id ?"修改成功":'添加成功',
      type: "success",
    });
    //切换页面
    show.value = 0;
    // 刷新页面
    getData();
  } catch (e) {
    ElMessage({
      message: addParams.value.id ?"修改失败":'添加失败',
      type: "error",
    });
  }
};
// 读写模式切换
// blur
let toLook = (row: any, index: any) => {
  //判断当前输入内容是否合法
  // 输入空格
  if (row.valueName.trim() === "") {
    //弹框
    ElMessage({
      message: "请勿输入空格",
      type: "error",
    });
    //删除输入内容
    addParams.value.attrValueList.splice(index, 1);
    return;
  }
  // 重复内容
  let result = addParams.value.attrValueList.findIndex((item: any) => {
    if (row != item) {
      return row.valueName == item.valueName;
    }
  });
  if (result !== -1) {
    //弹框
    ElMessage({
      message: "请勿输入重复内容",
      type: "error",
    });
    //删除输入内容
    addParams.value.attrValueList.splice(index, 1);
    return;
  }

  //将show状态变为false,显示div
  row.show = false;
};
//write
let toWrite = (row: any, index: any) => {
  //修改show状态为true,显示input
  row.show = true;
  //   通过nvxtTick获取渲染后的DOM
  nextTick(() => {
    // 鼠标聚焦时间
    formArr.value[index].focus();
  });
};

//表单校验规则
// 获取表单ref
let formVC = ref();
// 自定义校验规则
let validatorAttrName = (rule: any, value: any, callBack: any) => {
  // rule 表单校验规则
  // value 输入内容
  // callback 放行函数
  if (/^[\u4e00-\u9fa5]{2,4}$/.test(value)) {
    callBack();
  } else {
    callBack(new Error("属性名称为2-4位中文"));
  }
};
// 表单校验
let rules = {
  attrName: { required: true, trigger: "change", validator: validatorAttrName },
};
//气泡框确认按钮回调
let deleteOne = (index: number) => {
  addParams.value.attrValueList.splice(index, 1);
};
//修改按钮
let edit = (row: any) => {
  // 深拷贝当前点击的数据
  addParams.value = cloneDeep(row);
  // 切换页数
  show.value = 1;
};

//场景0删除按钮的回调
let clear = async (row: any) => {
    console.log(row.id)
  try {
    await deleteAttr(row.id);
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    getData();
  } catch (e) {
    ElMessage({
      message: "删除失败",
      type: "error",
    });
  }
};

// 请求封装
const getData = async () => {
  //准备参数
  let c1Id = categoryStore.c1Id,
    c2Id = categoryStore.c2Id,
    c3Id = categoryStore.c3Id;

  //发请求
  let result: any = await attrInfo(c1Id, c2Id, c3Id);
  data.value = result;
};
//卸载
onUnmounted(() => {
  //组件卸载,将数据清空
  categoryStore.c1Arr = [];
  categoryStore.c2Arr = [];
  categoryStore.c3Arr = [];
  categoryStore.c1Id = "";
  categoryStore.c2Id = "";
  categoryStore.c3Id = "";
});
</script>

<style scoped>
</style>